<template>
  <!--  遮罩-->
  <div class="min-h-screen bg-gray-100 p-8">
    <!-- 加载遮罩 -->
    <div
      v-if="loading"
      class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center"
    >
      <div class="bg-white rounded-lg p-8 flex flex-col items-center space-y-4">
        <el-icon class="loading-icon text-6xl text-blue-500">
          <Loading />
        </el-icon>
        <span class="text-gray-700 text-lg">加载中，请稍候...</span>
        <div class="w-full mt-4">
          <div class="text-sm text-gray-600 mb-2">AI 分析进度</div>
          <div class="flex items-center space-x-2">
            <div class="flex-1 bg-gray-200 rounded-full h-2">
              <div
                class="bg-blue-500 h-2 rounded-full transition-all duration-300"
                :style="{ width: `${progress}%` }"
              ></div>
            </div>
            <span class="text-sm text-gray-600">{{ progress }}%</span>
          </div>
          <div class="mt-3 text-sm text-gray-600">{{ currentStep }}</div>
        </div>
      </div>
    </div>
    <div id="viewQuestionView">
      <a-row :gutter="[24, 24]">
        <a-col :md="12" :xs="24">
          <a-tabs default-active-key="question">
            <a-tab-pane key="question" title="题目">
              <a-card v-if="question" :title="question.title">
                <a-descriptions
                  title="判题条件"
                  :column="{ xs: 1, md: 2, lg: 3 }"
                >
                  <a-descriptions-item label="时间限制">
                    {{ question.judgeConfig.timeLimit ?? 0 }}
                  </a-descriptions-item>
                  <a-descriptions-item label="内存限制">
                    {{ question.judgeConfig.memoryLimit ?? 0 }}
                  </a-descriptions-item>
                  <a-descriptions-item label="堆栈限制">
                    {{ question.judgeConfig.stackLimit ?? 0 }}
                  </a-descriptions-item>
                </a-descriptions>

                <h3>题目内容</h3>

                <MdViewer :value="question.content || ''" />
                <template #extra>
                  <a-space wrap>
                    <a-tag
                      v-for="(tag, index) of question.tags"
                      :key="index"
                      color="green"
                      >{{ tag }}
                    </a-tag>
                  </a-space>
                </template>
              </a-card>
            </a-tab-pane>
            <a-tab-pane key="comment" title="答案" disabled>
              暂时无法查看答案</a-tab-pane
            >
            <a-tab-pane key="answer" title="提交记录">
              <div style="font-size: larger; font-weight: bolder">提交记录</div>
              <div>
                <!--              时间复杂度分析弹窗-->
                <a-modal
                  v-model:visible="visibleTime"
                  @ok="handleTimeOk"
                  @cancel="handleTimeCancel"
                >
                  <template #title> 时间复杂度 </template>
                  <!--                todo 时间复杂度响应道这里-->
                  <div style="font-size: 25px">
                    您本次提交的代码时间复杂度为o({{ TimeAndSpace }})
                  </div>
                </a-modal>
                <!--              空间复杂度分析弹窗-->
                <a-modal
                  v-model:visible="visibleSpace"
                  @ok="handleSpaceOk"
                  @cancel="handleSpaceCancel"
                >
                  <!--                  done 空间复杂度等等遮罩的完成-->
                  <template #title> 空间复杂度 </template>
                  <div style="font-size: 25px">
                    您本次提交的代码空间复杂度为o({{ TimeAndSpace }})
                  </div>
                </a-modal>
                <!--                Ai代码分析页面-->
                <MarkdownPreviewModal
                  :markdown="yourMarkdownContent"
                  :visible="visibleAi"
                  @update:visible="showModal = $event"
                />
                <a-card
                  v-for="(record, index) in dataList"
                  :key="index"
                  style="margin-top: 16px; border-radius: 10px"
                >
                  <div style="display: flex">
                    <p style="width: 120px">{{ record.judgeInfo.message }}</p>
                    <p style="margin-right: 15px; margin-top: -4px">
                      <a-tag style="border-radius: 30%; color: #a2464e">{{
                        record.language
                      }}</a-tag>
                    </p>
                    <p style="margin-right: 15px; margin-top: -6px">
                      <a-button @click="handleTimeClick(record.id)"
                        >时间复杂度分析</a-button
                      >
                    </p>
                    <p style="margin-right: 15px; margin-top: -6px">
                      <a-button @click="handleSpaceClick(record.id)"
                        >空间复杂度分析</a-button
                      >
                    </p>

                    <p style="margin-right: 15px; margin-top: -6px">
                      <a-button @click="aiAnaysic(record.id)">Ai分析</a-button>
                    </p>
                    <p style="margin-right: 15px">
                      {{ moment(record.createTime).format("YYYY-MM-DD") }}
                    </p>
                  </div>
                </a-card>

                <a-pagination
                  :current="searchParams.current"
                  :pageSize="searchParams.pageSize"
                  :total="total"
                  @change="onPageChange"
                  showTotal
                />
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-col>
        <a-col :md="12" :xs="24">
          <a-form :model="form" layout="inline">
            <a-form-item
              field="language"
              label="编程语言"
              style="min-width: 240px"
            >
              <a-select
                v-model="form.language"
                :style="{ width: '320px' }"
                placeholder="选择编程语言"
              >
                <a-option>java</a-option>
                <a-option>cpp</a-option>
                <a-option>python</a-option>
              </a-select>
            </a-form-item>
          </a-form>
          <CodeEditor
            :value="form.code as string"
            :language="form.language"
            :handle-change="changeCode"
          />
          <FanKui style="margin-top: 10px" />
          <a-divider size="0" />
          <a-button type="primary" style="min-width: 200px" @click="doSubmit">
            提交代码
          </a-button>

          <div>
            <div style="float: right">
              <AIAssistantSvg @click="toggleChatAi" v-if="!isChatVisible" />
              <CancelSvg
                v-if="isChatVisible"
                @click="closeChatAi"
                width="50"
                height="50"
              />
            </div>

            <ChatAi
              v-if="isChatVisible"
              :style="chatStyle"
              @close="isChatVisible = false"
            />
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup lang="ts">
//题目详情页
import { onMounted, ref, watchEffect, withDefaults, defineProps } from "vue";
import message from "@arco-design/web-vue/es/message";
import CodeEditor from "@/components/CodeEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import { Loading } from "@element-plus/icons-vue";
import {
  QuestionSubmitAddRequest,
  QuestionVO,
} from "../../../xiongoj_backendapi";
import moment from "moment/moment";
import ChatAi from "@/components/admin/ChatAi.vue";
import CancelSvg from "@/components/admin/CancelSvg.vue";
import AIAssistantSvg from "@/components/admin/AIAssistantSvg.vue";
import { IconEye } from "@arco-design/web-vue/es/icon";
import axios from "axios";
interface Props {
  id: string;
}
// -----查看细节
const specificModalVisible = ref(false);
const triggerSpecificModal = (id: any) => {
  specificModalVisible.value = true;
};

const props = withDefaults(defineProps<Props>(), {
  id: () => "",
});

const question = ref<QuestionVO>();
const TimeRant = ref();
//时间复杂度

/**
 * 加载这道题的题目信息
 */
const loadData = async () => {
  const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
    props.id as any
  );
  if (res.code === 0) {
    question.value = res.data;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const form = ref<QuestionSubmitAddRequest>({
  language: "java",
  code: "",
});

/**
 * 提交代码
 */
const doSubmit = async () => {
  if (!question.value?.id) {
    return;
  }
  const res = await QuestionControllerService.doQuestionSubmitUsingPost({
    ...form.value,
    questionId: question.value.id,
  });

  if (res.code === 0) {
    message.success("运行成功，请点击提交记录查看");
    await loadDataInner();
  } else {
    message.error("提交失败," + res.message);
  }
};

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});
//改变提交代码语言
const changeCode = (value: string) => {
  form.value.code = value;
};
//打开ai聊天界面的窗口
const isChatVisible = ref(false);

// 控制聊天框出现的位置
const chatStyle = ref({
  position: "absolute",
  right: "200px", // 调整位置
  bottom: "20px", // 调整位置
});

const toggleChatAi = () => {
  isChatVisible.value = true; // 显示 ChatAi
};

const closeChatAi = () => {
  isChatVisible.value = false; // 关闭 ChatAi
};

//加载提交记录数据--------------------------------------------------------------------------------------------------------------------------------

import {
  QuestionControllerService,
  QuestionSubmitQueryRequest,
} from "../../../xiongoj_backendapi";
import FanKui from "@/components/FanKui.vue";

// 定义响应式变量
const dataList = ref([]);
const total = ref(0);
const searchParams = ref<QuestionSubmitQueryRequest>({
  questionId: undefined,
  language: undefined,
  pageSize: 4,
  current: 1,
});

// 加载数据函数
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import MarkdownPreviewModal from "@/components/MarkdownPreviewModal.vue";
const store = useStore();
const loadDataInner = async () => {
  const res = await QuestionControllerService.listQuestionSubmitByPageUsingPost(
    {
      ...searchParams.value,
      sortField: "createTime",
      sortOrder: "descend",
      userId: store.state.user?.loginUser?.userId,
      questionId: question.value?.id,
    }
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

// 监听 searchParams 变量，改变时触发页面的重新加载
watchEffect(() => {
  loadDataInner();
});

// 页面加载时，请求数据
onMounted(() => {
  loadDataInner();
});

// 分页变化处理
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};
//编写三个弹窗--------------------------------------------------------------------------------------------------------------
const visibleTime = ref(false);
const visibleSpace = ref(false);
const visibleAi = ref(false);
const TimeAndSpace = ref("n");
const yourMarkdownContent = ref();
// todo
const updateProgress = async () => {
  const steps = [
    { progress: 20, message: "正在发送代码到后端..." },
    { progress: 40, message: "发送成功..." },
    { progress: 60, message: "后端接受成功..." },
    { progress: 80, message: "生成分析结果..." },
    { progress: 100, message: "分析完成" },
  ];

  for (const step of steps) {
    progress.value = step.progress;
    currentStep.value = step.message;
    await new Promise((resolve) => setTimeout(resolve, 400));
  }
};
const handleTimeClick = async (id: string) => {
  // 开始请求，显示加载遮罩
  loading.value = true;
  progress.value = 0;
  currentStep.value = "初始化分析环境...";
  try {
    console.log(dataList.value);
    const targetRecord = dataList.value.find((item) => item.id === id);

    if (targetRecord != null) {
      const response = await axios.get("http://localhost:8101/api/TimeRant", {
        params: {
          id: targetRecord.id,
        },
      });
      TimeAndSpace.value = response.data;
    }

    // 模拟请求过程中的进度更新，你也可以根据实际情况决定是否保留这部分
    await updateProgress();
  } catch (error) {
    console.error("请求时间复杂度分析失败:", error);
  } finally {
    // 请求完成，隐藏加载遮罩
    loading.value = false;
    visibleTime.value = true;
  }
};
const handleSpaceClick = async (id: string) => {
  // 开始请求，显示加载遮罩
  loading.value = true;
  progress.value = 0;
  currentStep.value = "初始化分析环境...";

  try {
    console.log(dataList.value);
    const targetRecord = dataList.value.find((item) => item.id === id);

    if (targetRecord != null) {
      const response = await axios.get("http://localhost:8101/api/SpaceRant", {
        params: {
          id: targetRecord.id,
        },
      });
      TimeAndSpace.value = response.data;
    }

    // 模拟请求过程中的进度更新，你也可以根据实际情况决定是否保留这部分
    await updateProgress();
  } catch (error) {
    console.error("请求时间复杂度分析失败:", error);
  } finally {
    // 请求完成，隐藏加载遮罩
    loading.value = false;
    visibleSpace.value = true;
  }
};
const showModal = ref(false);
const aiAnaysic = async (id: string) => {
  // 开始请求，显示加载遮罩
  loading.value = true;
  progress.value = 0;
  currentStep.value = "初始化分析环境...";
  // todo
  try {
    const targetRecord = dataList.value.find((item) => item.id === id);

    if (targetRecord != null) {
      const response = await axios.get(
        "http://localhost:8101/api/AiCodeAnalysis",
        {
          params: {
            questionId: question.value?.id,
            questionSubmitId: targetRecord.id,
          },
        }
      );
      yourMarkdownContent.value = response.data;
    }

    // 模拟请求过程中的进度更新，你也可以根据实际情况决定是否保留这部分
    await updateProgress();
  } catch (error) {
    console.error("请求时间复杂度分析失败:", error);
  } finally {
    // 请求完成，隐藏加载遮罩
    loading.value = false;
    visibleAi.value = true;
  }
};
const handleTimeOk = () => {
  visibleTime.value = false;
};
const handleSpaceOk = () => {
  visibleSpace.value = false;
};
const handleTimeCancel = () => {
  visibleTime.value = false;
};
const handleSpaceCancel = () => {
  visibleSpace.value = false;
};
// ---------------------------------------------------处理遮罩-----------------------------------------------------------------
const loading = ref(false);
const progress = ref(0);
const currentStep = ref("AI分析代码中....");

// 刷新数据
const refreachData = () => {
  loadDataInner();
  ElMessage.success("刷新提交记录成功！");
};
</script>

<style>
#viewQuestionView {
  max-width: 1400px;
  margin: 0 auto;
}

#viewQuestionView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}
.custom-modal {
  /* 以下样式用于使弹窗在全局居中 */
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
